package com.lxyk.controller;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.lxyk.pojo.MainMenu;
import com.lxyk.service.HistoryService;
import com.lxyk.service.WorkerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.*;


/**
 * @ClassName MainMenuController
 * @Description TODO
 * @Author FJQ
 * @Date 2022/10/29 14:21
 * @Version 1.0
 **/
@Controller
@RequestMapping("/main")
@Slf4j
public class MainMenuController {
    @Autowired
    private WorkerService workerService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/mainMenu")
    @ResponseBody
    public List<MainMenu> mainMenu(){
        List<MainMenu> mainMenu = redisTemplate.opsForList().range("mainMenu", 0, -1);

        //判断 mainMenu 是否为null
        if(mainMenu == null || mainMenu.size() == 0){
            // redis没有数据
            log.info("redis没有数据，查询数据库");
            // 从数据库中查询
            List<MainMenu> list = new ArrayList<>();
            Map<Integer, Integer> map = new HashMap<>();
            historyService.listHistory().forEach(h ->{
                map.put(h.getWorkerId(),map.getOrDefault(h.getWorkerId(),0)+h.getSendWaterCount());
            });
            workerService.listWorker().forEach(e -> {
                MainMenu main = new MainMenu();
                main.setWorkerName(e.getWorkerName());
                Integer count = map.get(e.getWid());
                main.setSendWaterCount(count == null ? 0 : count);
                list.add(main);
            });
            if (list.size() < 12){
                 mainMenu.addAll(list);
            }
            for (int i = 0; i < 12; i++) {
                mainMenu.add(list.get(i));
            }
            Collections.sort(mainMenu, (o1,o2) ->{
                        if(o1.getSendWaterCount() > o2.getSendWaterCount()){
                            return 1;
                        }else if (o1.getSendWaterCount()  < o2.getSendWaterCount()){
                            return -1;
                        }else {
                            return 0;
                        }
                    });
            redisTemplate.opsForList().leftPushAll("mainMenu",mainMenu);
        }else {
            log.info("走redis...");
        }
        return mainMenu;
    }

}
